package com.plugins;


import com.utils.DataMap;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;

/**
 * Project: tobe-better-coder
 * Package: com.plugins
 *
 * @author : Mr.xu
 * @date : 2023/9/25 22:21
 */
@Intercepts(@Signature(type = ResultSetHandler.class,method = "handleResultSets",args = Statement.class))
@Component
public class DataDesensitizationPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        List<Object> objects = (List<Object>) invocation.proceed();
        objects.forEach(this::desensitization);
        return objects;
    }

    private void desensitization(Object object){
        Class<?> cls = object.getClass();
        MetaObject metaObject = SystemMetaObject.forObject(object);
        Field[] list = cls.getDeclaredFields();
        for (Field field : list) {
            if (DataMap.set.contains(field.getName())) {
                if (metaObject.getValue(field.getName()).getClass() == String.class) {
                    metaObject.setValue(field.getName(), "***");
                }
            }
        }
    }
}